<?php

namespace polymerize\order\module\pay;

use app\common\InstanceTrait;
use app\common\OsType;
use app\common\PayType;
use app\model\User as UserModel;
use app\model\VipOrder;
use app\service\AlipayService;
use app\service\OrderService;
use app\service\WechatService;

class PayVip
{
    use InstanceTrait;

    /**
     * VIP支付购买
     *
     * @param int    $uid
     * @param int    $osType
     * @param string $vipType
     * @param int    $payType
     * @param int    $disposableGoods
     * @return array
     */
    public function payVip(int $uid, int $osType, string $vipType, int $payType, int $disposableGoods): array
    {
        if (!$payType) return ['code' => 400, 'msg' => '支付渠道未开通'];

//        $where1[]      = ['type', '=', $vipType];
//        $where1[]      = ['os_type', '=', $osType];
//        $where1[]      = ['status', '=', 1];
//        $vipConfigInfo = VipConfig::getOne($where1);
//        if (!$vipConfigInfo) return ['code' => 400, 'msg' => '会员类型不存在'];

        //微信小程序支付
        if ($osType == OsType::OS_TYPE_MICRO_APP->value) {
            $where[]  = ['id', '=', $uid];
            $wxOpenid = UserModel::where($where)->value('wx_openid');
            if (!$wxOpenid) return ['code' => 400, 'msg' => '用户的微信openid不存在'];
        }

        //苹果一次性商品，用户只能购买一次
        if (($disposableGoods == 1) && ($payType == 3)) {
            $where2[]     = ['vip_type', '=', $vipType];
            $where2[]     = ['vip_config_id', '=', 1];
            $where2[]     = ['pay_type', '=', 3];
            $where2[]     = ['os_type', '=', 2];
            $where2[]     = ['status', '=', 1];
            $where2[]     = ['uid', '=', request()->uid];
            $vipOrderInfo = VipOrder::getOne($where2);
            if ($vipOrderInfo) return ['code' => 400, 'msg' => '已支付'];
        }

        $data    = [
            'uid'           => $uid,
            'money'         => 0.01,
            'day'           => 123,
            'vip_type'      => $vipType,
            'vip_config_id' => 1,
            'pay_type'      => $payType,
            'os_type'       => $osType,
        ];
        $orderNo = OrderService::instance()->setVipOrder($data);
        $orderInfo = VipOrder::getOne(['order_no' => $orderNo]);

        // 支付宝H5支付成功后回调
        //https://qstest.owneweb.com/h5/payCallback/alipay?charset=UTF-8&out_trade_no=vip165633LxtX&method=alipay.trade.wap.pay.return&total_amount=0.10&sign=OXuFA7CQ6&trade_no=20220562779&auth_app_id=20226946&version=1.0&app_id=202106&sign_type=RSA2&seller_id=2088441359658&timestamp=2022-05-24+17%3A14%3A05
        $aliQuitUrl = $ali_return_url = WEB_URL . "/h5/payCallback/alipay";
        $title      = env('APP_NAME', '欧文互联');

        try {
            $payment = match ($osType) {
                // IOS系统用H5支付
                OsType::OS_TYPE_IOS->value => match ($payType) {
                    PayType::PAY_ALIPAY->value => AlipayService::instance()->_h5_pay($orderInfo, $aliQuitUrl, $ali_return_url, 'GET', $title),
                    PayType::PAY_WECHAT->value => WechatService::instance()->_h5_pay($orderInfo, $title),
                    PayType::PAY_APPLEPAY->value => 'apple',
                },
                // 微信小程序系统用H5支付
                OsType::OS_TYPE_MICRO_APP->value => match ($payType) {
                    PayType::PAY_WECHAT->value => WechatService::instance()->jsapiPay($wxOpenid, $orderInfo, $title),
                },
                default => match ($payType) {
                    PayType::PAY_ALIPAY->value => AlipayService::instance()->_h5_pay($orderInfo, $aliQuitUrl, $ali_return_url, 'GET', $title),
                    PayType::PAY_WECHAT->value => WechatService::instance()->_h5_pay($orderInfo, $title),
                    PayType::PAY_APPLEPAY->value => 'apple',
                },
            };
        } catch (\Throwable $e) {
            return ['code' => 400, 'msg' => $e->getMessage()];
        }

        if (!$payment) return ['code' => 400, 'msg' => '支付payment获取失败'];
        $data = [
            'pay_type' => $payType,
            'payment'  => json_encode($payment)
        ];

        //统一格式
        if (isset($payment['h5_url'])) {
            $payment               = $payment['h5_url'];
            $data['wechat_h5_url'] = $payment;
        }
        $res = VipOrder::updateDataCache(['order_no' => $orderNo], $data);

        if (!$res) return ['code' => 400, 'msg' => '支付数据更新失败'];

        return ['code' => 200, 'data' => ['order_no' => $orderNo, 'payment' => $payment, 'pay_type' => $payType]];
    }
}
